<?php
class ControllerSaleMail extends AdminController {
	public function index() {
		M('sale/mail', 'mod_mail');
		$this->getList();
	}

	public function insert() {
		M('sale/mail', 'mod_mail');
		if ($this->request->isPost()) {
			$this->mod_mail->addMail($this->request->post);

			$this->session->set_flashdata('success', $this->_['text_success']);
			$this->redirect(UA('sale/mail'));
		}
		$this->getForm();
	}

	public function update() {
		M('sale/mail', 'mod_mail');
		if ($this->request->isPost()) {
			$this->mod_mail->editMail($this->request->get['mail_id'], $this->request->post);
				
			$this->session->set_flashdata('success', $this->_['text_success']);
			$this->redirect(UA('sale/mail'));
		}
		$this->getForm();
	}

	public function delete() {
		M('sale/mail', 'mod_mail');
		if ($this->request->post['selected']) {
			$this->mod_mail->deleteMail($this->request->post['selected']);
			$this->session->set_flashdata('success', $this->_['text_success']);
			$this->redirect(UA('sale/mail'));
		}
		$this->getList();
	}

	protected function getList() {
		$this->document->setTitle($this->_['heading_title']);

		$qf = new Query_filter();
		$total = $this->mod_mail->getTotalMails($qf);
		$this->data['mails'] = $this->mod_mail->getMails($qf);
		$this->data['pagination'] = $this->pagination($total)->render();
	
		$this->data['filter_subject'] = $qf->get('filter_subject');
		
		$this->display('sale/mail_list.tpl');
	}

	protected function getForm() {
		$this->document->addScript(ROOT . 'static/javascript/jquery/jquery.validate.js');
		$this->document->setTitle($this->_['heading_title']);
		$mail_id = G('mail_id');
		if ($mail_id) {
			$this->data['action'] = UA('sale/mail/update', "mail_id=$mail_id");
			if (!$this->request->isPost()) {
				$this->vo->data = $this->mod_mail->getMail($mail_id);
			}
		}
		else {
			$this->data['action'] = UA('sale/mail/insert');
		}
		
		$this->display('sale/mail_form.tpl');
	}
}